package br.com.localfloripa.listeners;

import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;

@SuppressWarnings({"serial"})
public class LoginErrorPhaseListener implements PhaseListener {

	@Override
	public void afterPhase(PhaseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
		Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
		Exception validationErrorException = (Exception) sessionMap.get(WebAttributes.AUTHENTICATION_EXCEPTION);
		if(validationErrorException instanceof BadCredentialsException) {
			sessionMap.put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
			ResourceBundle bundle = ResourceBundle.getBundle("messages.MessageBundle");
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					bundle.getString("messages.sumary.error"), bundle.getString("manager.security.login.error")));	
		}

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}
